const Promise = require('bluebird');
const bcrypt = Promise.promisifyAll(require('bcrypt'));

const { crasheyeBookshelf } = require('../../config/db');


const crasheyeUser = crasheyeBookshelf.Model.extend({
  tableName: 'user',
}, {
  login: Promise.method(function (email, password) {
    return new this({ email: email.toLowerCase().trim() }).fetch({ require: true })
    .tap(function (user) {
      return bcrypt.compareAsync(password, user.get('password'))
          .then(function (res) {
            if (!res) throw new Error('Invalid password');
          });
    });
  }),
});

exports.crasheyeUserModel = crasheyeUser;
